import config from '../config/index.js';
import { checkUserPermission } from './authService.js';

/**
 * 获取对话列表
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
export async function getConversations(req, res) {
  try {
    // 从查询参数获取必要信息
    const { last_id, limit = 20, appId, appuserId, platform = "agency" } = req.query;
    let user = `${platform}_${appuserId}`;

    // 验证用户权限
    const authResult = await checkUserPermission(appId, appuserId, platform);
    if (!authResult.success) {
      return res.status(403).send(authResult.message);
    }

    const APIkey = authResult.APIkey;

    // 构建请求URL
    let fetchURL = `${config.server.dify}/conversations?user=${user}&limit=${limit}`;
    if (last_id) {
      fetchURL += `&last_id=${last_id}`;
    }

    // 向Dify发送请求
    const response = await fetch(fetchURL, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${APIkey}`
      }
    });

    if (!response.ok) {
      console.error(`获取对话列表失败: ${response.status} ${response.statusText}`);
      return res.status(response.status).json({
        error: "获取对话列表失败",
        details: response.statusText
      });
    }

    // 获取响应数据并返回
    const conversationsData = await response.json();
    return res.json({
      code: 1000,
      ...conversationsData
    })
  } catch (error) {
    console.error("获取对话列表错误:", error);
    return res.status(500).json({ error: "服务器内部错误", details: error.message });
  }
}

// 删除会话
export const deleteConversation = async (req, res) => {
  try {
    const { conversation_id, appId, appuserId, platform } = req.body;
    let user = `${platform}_${appuserId}`;

    // 验证用户权限
    const authResult = await checkUserPermission(appId, appuserId, platform);
    if (!authResult.success) {
      return res.status(403).send(authResult.message);
    }

    const APIkey = authResult.APIkey;

    const response = await fetch(`${config.server.dify}/conversations/${conversation_id}`, {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${APIkey}`
      },
      body: JSON.stringify({ user })
    });

    if (!response.ok) {
      console.error(`删除会话失败: ${response.status} ${response.statusText}`);
      return res.status(response.status).json({
        error: "删除会话失败",
        details: response.statusText
      });
    }

    const conversationsData = await response.json();
    console.log("%c Line:82 🍿 conversationsData", "color:#ea7e5c", conversationsData);
    return res.json({
      code: 1000,
      ...conversationsData
    });
  } catch (error) {
    console.log("%c Line:88 🍷 error", "color:#4fff4B", error);
    console.error("删除会话失败:", error.response?.data || error.message);
    return res.status(error.response?.status || 500).json({
      error: error.response?.data || "删除会话失败"
    });
  }
};


// 会话重命名
export const renameConversation = async (req, res) => {
  try {
    const { conversationId } = req.params;
    const { name, auto_generate, user } = req.body;
    const apiKey = req.headers.authorization?.split(" ")[1];

    if (!apiKey) {
      return res.status(401).json({ error: "未提供授权信息" });
    }

    if (!user) {
      return res.status(400).json({ error: "用户标识不能为空" });
    }

    const response = await axios.post(`${DIFY_BASE_URL}/conversations/${conversationId}/name`, {
      name,
      auto_generate,
      user
    }, {
      headers: getHeaders(apiKey)
    });

    return res.status(200).json(response.data);
  } catch (error) {
    console.error("会话重命名失败:", error.response?.data || error.message);
    return res.status(error.response?.status || 500).json({
      error: error.response?.data || "会话重命名失败"
    });
  }
};

// 获取会话历史消息
export const getConversationMessages = async (req, res) => {
  try {
    const { conversation_id, appId, appuserId, platform = "agency", first_id, limit } = req.query;

    const authResult = await checkUserPermission(appId, appuserId, platform);
    if (!authResult.success) {
      return res.status(403).send(authResult.message);
    }

    const APIkey = authResult.APIkey;
    if (!appuserId) {
      return res.status(400).json({ error: "用户标识不能为空" });
    }
    let user = `${platform}_${appuserId}`;

    if (!conversation_id) {
      return res.status(400).json({ error: "会话ID不能为空" });
    }
    
    // console.log("%c Line:157 🍑 conversation_id", "color:#ffdd4d", conversation_id, user, first_id, limit,APIkey);
    let url=`${config.server.dify}/messages?conversation_id=${conversation_id}&user=${user}&limit=${limit}`
    const response = await fetch(url, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${APIkey}`
      }
    });

    if (!response.ok) {
      console.error(`获取会话历史消息失败: ${response.status} ${response.statusText}`);
      return res.status(response.status).json({
        error: "获取会话历史消息失败",
        details: response.statusText
      });
    }
    const conversationsData = await response.json();

    return res.status(200).json({
      code: 1000,
      ...conversationsData
    });
  } catch (error) {
    console.error("获取会话历史消息失败:", error.response?.data || error.message);
    return res.status(error.response?.status || 500).json({
      error: error.response?.data || "获取会话历史消息失败"
    });
  }
};

// 获取下一轮建议问题列表
export const getSuggestedQuestions = async (req, res) => {
  try {
    const { messageId } = req.params;
    const { user } = req.query;
    const apiKey = req.headers.authorization?.split(" ")[1];

    if (!apiKey) {
      return res.status(401).json({ error: "未提供授权信息" });
    }

    if (!user) {
      return res.status(400).json({ error: "用户标识不能为空" });
    }

    const response = await axios.get(`${DIFY_BASE_URL}/messages/${messageId}/suggested`, {
      headers: getHeaders(apiKey),
      params: { user }
    });

    return res.status(200).json(response.data);
  } catch (error) {
    console.error("获取建议问题列表失败:", error.response?.data || error.message);
    return res.status(error.response?.status || 500).json({
      error: error.response?.data || "获取建议问题列表失败"
    });
  }
};